/*
 * 
 *
 * Created on 24 de abril de 2008, 03:18 PM
 */
package org.contabilidad.morosidad.inicial;

 
import org.mybeans.Sesion;
import org.mybeans.RegimenBeans;
 
import org.mybeans.VehiculosBeans;
import org.vehiculos.busquedas.VehiculosBusquedaConPlacaFrame;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

/**
 *
 * @author  avbravo
 */
public class MorosidadInicialVehiculosAgregarFrame extends javax.swing.JFrame {

    Sesion sesion;
    VehiculosBeans vehiculosBeans;
    RegimenBeans regimenBeans;
    int Anio;
    String idRegimenFormulario;
    boolean focoBuscar = false;
    String Placa;
    int idVehiculo;
int year;
    
    public MorosidadInicialVehiculosAgregarFrame() {
        initComponents();
        sesion = new Sesion();
        vehiculosBeans = new VehiculosBeans();
        regimenBeans = new RegimenBeans();

        /*
         * Fondo
         */

         
         
         

        jPanelFondo.setOpaque(false);
        setContentPane(jPanelFondo);
        /*
         * fondo
         */

        java.util.Calendar ca = java.util.Calendar.getInstance();
        java.sql.Date mydate = new java.sql.Date(ca.getTimeInMillis());
        CargarSubGrupoRegimen();
        year = ca.get(java.util.Calendar.YEAR);
        this.Anio = year;
        jTextFieldAnio.setText(String.valueOf(this.Anio));

        AutoCompleteDecorator.decorate(this.jComboBoxSubGrupoRegimen);
        AutoCompleteDecorator.decorate(this.jComboBoxIdRegimen);


    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanelFondo = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldPlaca = new javax.swing.JTextField();
        jTextFieldVehiculo = new javax.swing.JTextField();
        jButtonBuscar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldAnio = new javax.swing.JTextField();
        jComboBoxIdRegimen = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jComboBoxSubGrupoRegimen = new javax.swing.JComboBox();
        jLabel13 = new javax.swing.JLabel();
        jTextFieldMonto = new javax.swing.JTextField();
        jButtonGuardar = new javax.swing.JButton();
        jButtonLimpiar = new javax.swing.JButton();
        jButtonVerImpuestos = new javax.swing.JButton();
        jButtonRegresar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Agregar Morosidad Inicial de Vehiculos");
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });

        jPanelFondo.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Placa");

        jLabel2.setText("Vehiculo");

        jTextFieldPlaca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldPlacaActionPerformed(evt);
            }
        });

        jTextFieldVehiculo.setEditable(false);

        jButtonBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/search.png"))); // NOI18N
        jButtonBuscar.setToolTipText("Buscar");
        jButtonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarActionPerformed(evt);
            }
        });

        jLabel3.setText("Año");

        jComboBoxIdRegimen.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBoxIdRegimenItemStateChanged(evt);
            }
        });
        jComboBoxIdRegimen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxIdRegimenActionPerformed(evt);
            }
        });

        jLabel7.setText("Regimen");

        jLabel4.setText("Subgrupo");

        jComboBoxSubGrupoRegimen.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBoxSubGrupoRegimenItemStateChanged(evt);
            }
        });
        jComboBoxSubGrupoRegimen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxSubGrupoRegimenActionPerformed(evt);
            }
        });

        jLabel13.setText("Monto");

        jButtonGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/save.png"))); // NOI18N
        jButtonGuardar.setToolTipText("Guardar");
        jButtonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGuardarActionPerformed(evt);
            }
        });

        jButtonLimpiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/escoba.png"))); // NOI18N
        jButtonLimpiar.setToolTipText("Limpiar");
        jButtonLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonLimpiarActionPerformed(evt);
            }
        });

        jButtonVerImpuestos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/view.png"))); // NOI18N
        jButtonVerImpuestos.setToolTipText("Ver");
        jButtonVerImpuestos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonVerImpuestosActionPerformed(evt);
            }
        });

        jButtonRegresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gif/regresar.jpeg"))); // NOI18N
        jButtonRegresar.setToolTipText("Regresar");
        jButtonRegresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRegresarActionPerformed(evt);
            }
        });

        jLabel5.setText("En este año se cargara la morosidad inicial como vigencia expirada.");

        javax.swing.GroupLayout jPanelFondoLayout = new javax.swing.GroupLayout(jPanelFondo);
        jPanelFondo.setLayout(jPanelFondoLayout);
        jPanelFondoLayout.setHorizontalGroup(
            jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelFondoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(jPanelFondoLayout.createSequentialGroup()
                        .addGap(102, 102, 102)
                        .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jComboBoxSubGrupoRegimen, javax.swing.GroupLayout.PREFERRED_SIZE, 473, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jComboBoxIdRegimen, javax.swing.GroupLayout.PREFERRED_SIZE, 389, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jLabel4)
                    .addComponent(jLabel7)
                    .addGroup(jPanelFondoLayout.createSequentialGroup()
                        .addComponent(jLabel13)
                        .addGap(65, 65, 65)
                        .addComponent(jTextFieldMonto, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanelFondoLayout.createSequentialGroup()
                        .addComponent(jButtonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonVerImpuestos, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanelFondoLayout.createSequentialGroup()
                        .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanelFondoLayout.createSequentialGroup()
                                .addComponent(jTextFieldPlaca, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(34, 34, 34)
                                .addComponent(jButtonBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanelFondoLayout.createSequentialGroup()
                                .addComponent(jTextFieldAnio, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(50, 50, 50)
                                .addComponent(jLabel5))
                            .addComponent(jTextFieldVehiculo, javax.swing.GroupLayout.PREFERRED_SIZE, 364, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(62, Short.MAX_VALUE))
        );
        jPanelFondoLayout.setVerticalGroup(
            jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelFondoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jButtonBuscar, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE)
                    .addComponent(jTextFieldPlaca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldVehiculo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldAnio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(8, 8, 8)
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jComboBoxSubGrupoRegimen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jComboBoxIdRegimen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel13)
                    .addComponent(jTextFieldMonto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanelFondoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonLimpiar, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonVerImpuestos, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonRegresar, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(24, 24, 24))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelFondo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelFondo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButtonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarActionPerformed

   VehiculosBusquedaConPlacaFrame vehiculosBusquedaConPlacaFrame = new VehiculosBusquedaConPlacaFrame();
    vehiculosBusquedaConPlacaFrame.setLocationRelativeTo(null);
    vehiculosBusquedaConPlacaFrame.setVisible(true);
    focoBuscar = true;
}//GEN-LAST:event_jButtonBuscarActionPerformed

private void jButtonRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRegresarActionPerformed

    dispose();
}//GEN-LAST:event_jButtonRegresarActionPerformed

private void jButtonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarActionPerformed

    try {
        String placa = this.jTextFieldPlaca.getText();
        if (placa == null || placa.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese la placa", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldPlaca.requestFocus();
            return;
        }


        String vehiculo = this.jTextFieldVehiculo.getText();
        if (vehiculo == null || vehiculo.equals("")) {
            JOptionPane.showMessageDialog(this, "seleccione un vehiculo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldVehiculo.requestFocus();
            return;
        }

        String IdRegimen = this.idRegimenFormulario;
        if (IdRegimen == null || IdRegimen.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese el codigo del regimen", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String temp = jTextFieldMonto.getText();

        if (temp == null || temp.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese el monto adeudado", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldMonto.requestFocus();
            return;
        }
        String sAnio = jTextFieldAnio.getText();
        if (sAnio == null || sAnio.equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese el año", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldAnio.requestFocus();
            return;
        }
        Anio = Integer.valueOf(sAnio);
        if (Anio <= 0) {
            JOptionPane.showMessageDialog(this, "Ingrese el año", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            jTextFieldAnio.requestFocus();
            return;
        }
        double monto = Double.parseDouble(jTextFieldMonto.getText());

        if (monto < 0.0) {
            JOptionPane.showMessageDialog(this, "El monto no debe ser menor que el limite inferior", "Mensaje", JOptionPane.WARNING_MESSAGE);
            this.jTextFieldMonto.setText("0.0");
            jTextFieldMonto.requestFocus();
            return;
        }

        if (sesion.Conectar() == false) {
            JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        String sqlquery = "select * from vigenciasexpiradas where idmunicipio = ? and id =? and tipoid ='vehiculos' and idregimen =? and anio = ? and activo='si' ";
        PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
        psquery.setString(1, sesion.getIdmunicipio());
        psquery.setString(2,String.valueOf(idVehiculo) );
        psquery.setString(3, IdRegimen);
        psquery.setInt(4, Anio);
        ResultSet rs = psquery.executeQuery();
        rs.next();
        int x = rs.getRow();

        if (x != 0) {

            JOptionPane.showMessageDialog(this, "Esta morosidad inicial ya fue asignada a este vehiculo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
sesion.con.close();
            this.jTextFieldMonto.setText("");
            return;
        }

        String sql = "INSERT into vigenciasexpiradas  VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
        PreparedStatement prest = sesion.con.prepareStatement(sql);


        double morosidadinicial = monto;
        double morosidadactual = monto;
        java.util.Calendar ca = java.util.Calendar.getInstance();
        java.sql.Date mydate = new java.sql.Date(ca.getTimeInMillis());

        prest.setInt(1, Anio);
        prest.setString(2, String.valueOf(idVehiculo));
        prest.setString(3, "vehiculos");
        prest.setString(4, IdRegimen);
        prest.setString(5, "si");
        prest.setString(6, "no");//pagado
        prest.setDouble(7, morosidadinicial);
        prest.setDouble(8, morosidadactual);
        prest.setString(9, sesion.getIdmunicipio());
        prest.setString(10, "inicial");
        prest.setString(11, sesion.getUsername());
        prest.setDate(12, mydate);


        int count = prest.executeUpdate();
        regimenBeans.setValor(monto);
        sesion.con.close();
        sesion.setIdVehiculo(String.valueOf(idVehiculo));
        JOptionPane.showMessageDialog(this, "Morosidad guardado exitosamente", "Mensaje", JOptionPane.INFORMATION_MESSAGE);


    } catch (Exception ex) {
        sesion.MostrarMensajeError("Error ", "Clase: MorosidadVehiculosAgregar.java\nGuardar()\n " + ex.getMessage().toString());
    }

}//GEN-LAST:event_jButtonGuardarActionPerformed

private void jButtonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLimpiarActionPerformed

    Limpiar();

}//GEN-LAST:event_jButtonLimpiarActionPerformed

private void jButtonVerImpuestosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonVerImpuestosActionPerformed

    MorosidadInicialVehiculosConsultarFrame morosidadInicialVehiculosConsultarFrame = new MorosidadInicialVehiculosConsultarFrame();
    morosidadInicialVehiculosConsultarFrame.setLocationRelativeTo(null);
    morosidadInicialVehiculosConsultarFrame.setVisible(true);
}//GEN-LAST:event_jButtonVerImpuestosActionPerformed

private void jTextFieldPlacaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldPlacaActionPerformed
    CargarVehiculos();

}//GEN-LAST:event_jTextFieldPlacaActionPerformed

private void jComboBoxIdRegimenItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxIdRegimenItemStateChanged
    //      }
    //start = false;
}//GEN-LAST:event_jComboBoxIdRegimenItemStateChanged

private void jComboBoxIdRegimenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxIdRegimenActionPerformed

    try {
        String temp = (String) jComboBoxIdRegimen.getSelectedItem();

        if (temp == null || temp.equals("")) {
            return;
        }
        int posicion = temp.indexOf("|");

        int posfinal = 0;
        if (posicion <= 0) {
            posfinal = 0;
        } else {
            posfinal = posicion - 1;
        }

        temp = temp.substring(0, posfinal);

        this.idRegimenFormulario = temp;
        ConsultarRegimen();


    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, "Error  " + ex.getMessage(), "ComboBox Regimen ActionPerformed", JOptionPane.ERROR_MESSAGE);
    }
}//GEN-LAST:event_jComboBoxIdRegimenActionPerformed

private void jComboBoxSubGrupoRegimenItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBoxSubGrupoRegimenItemStateChanged
}//GEN-LAST:event_jComboBoxSubGrupoRegimenItemStateChanged

private void jComboBoxSubGrupoRegimenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxSubGrupoRegimenActionPerformed

    try {
        String temp = (String) jComboBoxSubGrupoRegimen.getSelectedItem();
        int posicion = temp.indexOf("|");

        int posfinal = 0;
        if (posicion <= 0) {
            posfinal = 0;
        } else {
            posfinal = posicion - 1;
        }

        temp = temp.substring(0, posfinal);

        CargarRegimen(temp);


    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, "Error  " + ex.getMessage(), "ComboBox SubGrupoRegimen ActionPerformed", JOptionPane.ERROR_MESSAGE);
    }
}//GEN-LAST:event_jComboBoxSubGrupoRegimenActionPerformed

private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
    // TODO add your handling code here:
    if (focoBuscar) {
        Actualizar();
    }
    focoBuscar = false;
}//GEN-LAST:event_formWindowGainedFocus

    private void CargarSubGrupoRegimen() {
        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            String sqlquery = "select idsubgruporegimen, subgrupo from subgruporegimen where idmunicipio='" + sesion.getIdmunicipio() + "' and activo='si' order by idsubgruporegimen";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            ResultSet rs = psquery.executeQuery();
            jComboBoxSubGrupoRegimen.removeAllItems();
            int count = 0;
            while (rs.next()) {
                String idsubgruporegimen = rs.getString("idsubgruporegimen");
                idsubgruporegimen = idsubgruporegimen + " | " + rs.getString("subgrupo");
                jComboBoxSubGrupoRegimen.insertItemAt(idsubgruporegimen, count);
                count++;
            }
            if (count != 0) {
                jComboBoxSubGrupoRegimen.setSelectedIndex(0);
            }


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error. CargarSubGrupoRegimen()", JOptionPane.ERROR_MESSAGE);
        }
    }

    /*
     *
     * Cargar el regimen
     */
    private void CargarRegimen(String idsubgruporegimen) {
        try {
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            idsubgruporegimen = idsubgruporegimen.trim();
            String sqlquery = "select idregimen, valor, regimen from regimen where idmunicipio='" + sesion.getIdmunicipio() + "' and activo='si' and idsubgruporegimen='" + idsubgruporegimen + "' order by idregimen";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            ResultSet rs = psquery.executeQuery();
            jComboBoxIdRegimen.removeAllItems();
            int count = 0;
            while (rs.next()) {
                String idregimen = rs.getString("idregimen");
                idregimen = idregimen + " | " + String.valueOf(rs.getDouble("valor")) + " | " + rs.getString("regimen");
                jComboBoxIdRegimen.insertItemAt(idregimen, count);
                count++;
            }
            if (count != 0) {
                jComboBoxIdRegimen.setSelectedIndex(0);
            }


        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error" + ex.getMessage(), "CargarRegimen() ", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void ConsultarRegimen() {
        try {
            String IdRegimen = idRegimenFormulario;
            if (IdRegimen == null || IdRegimen.equals("")) {
                JOptionPane.showMessageDialog(this, "Ingrese el codigo del regimen", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            if (sesion.Conectar() == false) {
                JOptionPane.showMessageDialog(this, "No se pudo establecer la conexion", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }

            String sqlquery = "select regimen.* from regimen where regimen.idmunicipio = ? and idregimen = ?";
            PreparedStatement psquery = sesion.con.prepareStatement(sqlquery);
            psquery.setString(1, sesion.getIdmunicipio());
            psquery.setString(2, IdRegimen);
            ResultSet rs = psquery.executeQuery();
            rs.next();
            int x = rs.getRow();
            if (x == 0) {
                JOptionPane.showMessageDialog(this, "No existen registros de regimen con ese codigo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                sesion.con.close();
                return;
            }
            String activo = rs.getString("activo");
            if (activo.equals("no")) {
                JOptionPane.showMessageDialog(this, "Este regimen esta inactivo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            String IdSubGrupoRegimen = rs.getString("idsubgruporegimen");
            String Regimen = rs.getString("regimen");
            double Valor = rs.getDouble("valor");
            double LimiteInferior = rs.getDouble("limiteinferior");
            double LimiteSuperior = rs.getDouble("limiteSuperior");

            if (Regimen == null || Regimen.equals("")) {
                JOptionPane.showMessageDialog(this, "El regimen esta en blanco", "Mensaje", JOptionPane.WARNING_MESSAGE);
                return;
            }
            regimenBeans.setIdRegimen(IdRegimen);
            regimenBeans.setIdSubGrupoRegimen(IdSubGrupoRegimen);
            regimenBeans.setRegimen(Regimen);
            regimenBeans.setValor(Valor);
            regimenBeans.setLimiteInferior(LimiteInferior);
            regimenBeans.setLimiteSuperior(LimiteSuperior);


            repaint();

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "ConsultarRegimen() ", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MorosidadInicialVehiculosAgregarFrame().setVisible(true);
            }
        });
    }

    private void Limpiar() {

      this.jTextFieldMonto.setText("");
        jTextFieldPlaca.setText("");
        jTextFieldVehiculo.setText("");
        this.Anio = year;
        jTextFieldAnio.setText(String.valueOf(this.Anio));
    }

    private void CargarVehiculos() {

        try {
            String Placa = this.jTextFieldPlaca.getText();
            if (Placa == null || Placa.equals("")) {
                JOptionPane.showMessageDialog(this, "Ingrese la placa del vehiculo", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            vehiculosBeans.setPlaca(Placa);

            if (vehiculosBeans.ConsultarPorPlaca() == true) {

                if (vehiculosBeans.getPlaca() == null || vehiculosBeans.getPlaca().equals("")) {
                    JOptionPane.showMessageDialog(this, "Este vehiculo no tiene asiganda una placa...", "Mensaje", JOptionPane.INFORMATION_MESSAGE);
                    return;
                }


                vehiculosBeans.setTipoId(vehiculosBeans.getTipoId().toLowerCase());

                Actualizar();

            }

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }


    }

    private void Actualizar() {
        try {

            jTextFieldPlaca.setText(vehiculosBeans.getPlaca());
            this.Placa = vehiculosBeans.getPlaca();
            if (vehiculosBeans.getIdVehiculo() == null || vehiculosBeans.getIdVehiculo().equals("")) {
                this.idVehiculo = 0;
                JOptionPane.showMessageDialog(this, "Este vehiculo no tiene un codigo asignado", "Advertencia", JOptionPane.WARNING_MESSAGE);
            } else {
                this.idVehiculo= Integer.parseInt(vehiculosBeans.getIdVehiculo());
            }

            String dueno = "";
            if (vehiculosBeans.getDueno() == null) {
                dueno = "";
            } else {
                dueno = " Dueño " + vehiculosBeans.getDueno();
            }
            jTextFieldVehiculo.setText(vehiculosBeans.getMarca() + " Modelo: " + vehiculosBeans.getModelo() + dueno);

            String TipoId = vehiculosBeans.getTipoId();
            String idOld = vehiculosBeans.getId();
            TipoId = TipoId.toLowerCase();
           
            repaint();

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonBuscar;
    private javax.swing.JButton jButtonGuardar;
    private javax.swing.JButton jButtonLimpiar;
    private javax.swing.JButton jButtonRegresar;
    private javax.swing.JButton jButtonVerImpuestos;
    private javax.swing.JComboBox jComboBoxIdRegimen;
    private javax.swing.JComboBox jComboBoxSubGrupoRegimen;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanelFondo;
    private javax.swing.JTextField jTextFieldAnio;
    private javax.swing.JTextField jTextFieldMonto;
    private javax.swing.JTextField jTextFieldPlaca;
    private javax.swing.JTextField jTextFieldVehiculo;
    // End of variables declaration//GEN-END:variables
}
